package com.iplant.basic.serviceImpl.dao.bms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.DBSchemas;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.service.po.bms.BMSRegion;

public class BMSRegionDAO extends BaseDAO {

	private static BMSRegionDAO Instance = null;
	private static Logger logger = LoggerFactory.getLogger(BMSRegionDAO.class);

	private BMSRegionDAO() {
		super();

		setTableName("bms_region");
	}

	public static BMSRegionDAO getInstance() {
		if (Instance == null)
			Instance = new BMSRegionDAO();
		return Instance;
	}

	public void BMS_UpdateRegion(BMSEmployee wLoginUser, BMSRegion wRegion, OutResult<Integer> wErrorCode) {
		wErrorCode.set(0);

		try {
			if (wRegion == null || StringUtils.isEmpty(wRegion.Name)) {
				wErrorCode.set(ExceptionTypes.Parameter.getValue());
				return;
			}
			BMSRegion wRegionO = this.BMS_CheckRegion(wLoginUser, wRegion, wErrorCode);
			if (wRegionO.ID > 0) {
				wErrorCode.set(ExceptionTypes.Duplication.getValue());
			}
			if (wErrorCode.Result != 0)
				return;

			wRegion.FullName = "";
			if (wRegion.ParentID > 0) {
				wRegionO = this.BMS_QueryRegion(wLoginUser, wRegion.ParentID, "", wErrorCode);
				if (wErrorCode.Result != 0)
					return;

				if (wRegionO == null || wRegionO.ID <= 0) {
					wRegion.ParentID = 0;

				} else {

					wRegion.FullName = StringUtils.Format("{0}{1}/", wRegionO.FullName, wRegionO.Name);
				}
			}

			Map<String, Object> wParams = new HashMap<String, Object>();

			wParams.put("Name", wRegion.Name);
			wParams.put("Code", wRegion.Code);
			wParams.put("TypeID", wRegion.TypeID);
			wParams.put("ParentID", wRegion.ParentID);
			wParams.put("FullName", wRegion.FullName);
			wParams.put("Description", wRegion.Description);

			wParams.put("EditorID", wLoginUser.getID());
			wParams.put("EditTime", Calendar.getInstance());
			wParams.put("Active", wRegion.Active);

			if (wRegion.ID > 0) {
				wParams.put("ID", wRegion.ID);
				super.Update(super.getTableName("bms_region"), "ID", wParams);
			} else {
				wParams.put("CreatorID", wLoginUser.getID());
				wParams.put("CreateTime", Calendar.getInstance());
				wRegion.ID = super.Insert(super.getTableName("bms_region"), wParams);
			}

		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("BMS_UpdateRegion", ex);
		}
	}

	public void BMS_ActiveRegion(BMSEmployee wLoginUser, BMSRegion wRegion, int wActive,
			OutResult<Integer> wErrorCode) {
		wErrorCode.set(0);
		// 判断客户信息是否存在(中国：统一社会信用代码，国外:提醒是否有重复）

		try {
			if (wRegion == null || wRegion.ID <= 0) {
				wErrorCode.set(ExceptionTypes.Parameter.getValue());
				return;
			}

			Map<String, Object> wParams = new HashMap<String, Object>();

			wParams.put("ID", wRegion.ID);
			wParams.put("EditorID", wLoginUser.getID());
			wParams.put("EditTime", Calendar.getInstance());
			wParams.put("Active", wActive);
			super.Update(super.getTableName("bms_region"), "ID", wParams);

		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());

			logger.error("BMS_ActiveRegion", ex);
		}
	}

	public List<BMSRegion> BMS_QueryRegionList(BMSEmployee wLoginUser, String wName, int wTypeID, int wParentID,
			String wFullName, int wActive, Pagination wPagination, OutResult<Integer> wErrorCode) {
		return this.BMS_QueryRegionList(wLoginUser, -1, "", wName, wTypeID, wParentID, wFullName, wActive, wPagination,
				wErrorCode);
	}

	private List<BMSRegion> BMS_QueryRegionList(BMSEmployee wLoginUser, int wID, String wCode, String wName,
			int wTypeID, int wParentID, String wFullName, int wActive, Pagination wPagination,
			OutResult<Integer> wErrorCode) {
		List<BMSRegion> wBMSRegionList = new ArrayList<BMSRegion>();
		wErrorCode.set(0);

		try {

			// Step02:查询
			Map<String, Object> wParams = new HashMap<String, Object>();
			String wSQLText = "";
			wSQLText = StringUtils.Format(
					"Select t.*,t3.Name as CreatorName ,t4.Name as EditorName, t2.Name as ParentName,"
							+ " t2.Code as ParentCode,COUNT(t5.ID) AS ItemCount from {0}.bms_region t  "
							+ " left join {0}.bms_region t2 on t.ParentID=t2.ID "
							+ " left join {0}.mbs_user t3 on t.CreatorID=t3.ID "
							+ " left join {0}.mbs_user t4 on t.EditorID=t4.ID "
							+ " left join {0}.bms_region t5 on t5.ParentID=t.ID "
							+ " where (:ID<=0 or  t.ID=:ID) and (:Code =''''  or  t.Code=:Code)"
							+ " AND (:ParentID<0 or  t.ParentID=:ParentID) AND (:TypeID<=0 or  t.TypeID=:TypeID)  AND (:Active<0 or  t.Active=:Active) "
							+ " AND (:Name = '''' or  t.Name like :Name) AND (:FullName = '''' or  t.FullName like :Name) group by t.ID ",
					super.getDBName());

			wSQLText = this.DMLChange(wSQLText);

			wParams.put("ID", wID);
			wParams.put("Code", wCode);
			wParams.put("TypeID", wTypeID);
			wParams.put("ParentID", wParentID);
			wParams.put("Active", wActive);
			wParams.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));
			wParams.put("FullName", StringUtils.isEmpty(wFullName) ? "" : (wFullName + "%"));

			wBMSRegionList = super.QueryForList(wSQLText, wParams, wPagination, BMSRegion.class);

			// Step03:配置系统
		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("BMS_QueryRegionList", ex);
		}
		return wBMSRegionList;
	}

	public BMSRegion BMS_QueryRegion(BMSEmployee wLoginUser, int wID, String wCode, OutResult<Integer> wErrorCode) {
		BMSRegion wResult = new BMSRegion();
		wErrorCode.set(0);

		try {
			List<BMSRegion> wList = null;
			if (wID > 0) {
				wList = this.BMS_QueryRegionList(wLoginUser, wID, "", "", -1, -1, "", -1, Pagination.getDefault(),
						wErrorCode);

			} else if (StringUtils.isNotEmpty(wCode)) {
				wList = this.BMS_QueryRegionList(wLoginUser, -1, wCode, "", -1, -1, "", -1, Pagination.getDefault(),
						wErrorCode);
			}
			if (wList != null && wList.size() > 0) {
				wResult = wList.get(0);
			}
		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("BMS_QueryRegionByID", ex);
		}
		return wResult;
	}

	public BMSRegion BMS_CheckRegion(BMSEmployee wLoginUser, BMSRegion wBMSRegion, OutResult<Integer> wErrorCode) {
		BMSRegion wRegion = new BMSRegion();
		wErrorCode.set(0);

		try {

			// Step0:查询
			Map<String, Object> wParams = new HashMap<String, Object>();
			String wSQLText = StringUtils.Format("Select * from {0}.bms_region "
					+ " where ID!=:ID  AND ( (Name =:Name and ParentID=:ParentID) or (:Code != '''' and Code=:Code)) ",
					super.getDBName());
			wParams.clear();
			wParams.put("ID", wBMSRegion.ID);
			wParams.put("Name", wBMSRegion.Name);
			wParams.put("ParentID", wBMSRegion.ParentID);
			wParams.put("Code", wBMSRegion.Code);

			wSQLText = this.DMLChange(wSQLText);
			List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
			for (Map<String, Object> wSqlDataReader : wQueryResultList) {
				wRegion.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
				wRegion.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
				wRegion.Code = StringUtils.parseString(wSqlDataReader.get("Code"));
				wRegion.FullName = StringUtils.parseString(wSqlDataReader.get("FullName"));

				wRegion.ParentID = StringUtils.parseInt(wSqlDataReader.get("ParentID"));
				wRegion.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
				wRegion.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
				wRegion.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
				wRegion.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
				wRegion.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));

			}

		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("BMS_QueryRegion", ex);
		}
		return wRegion;
	}

}
